#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time, os
from PyQt4 import QtCore, QtGui
from Ui_dialog_export import *


class dialog_export(QtGui.QDialog, Ui_Dialog_export):
    def __init__(self,parent):
        super(dialog_export,self).__init__(parent)
        
        self.setupUi(self)
        self.parent=parent
        self.libmyCF=self.parent.libmyCF
        
        #SQL log info
        self.db_name = self.libmyCF.connector.db_name
        self.host = self.libmyCF.connector.sqlserver.host
        self.user = self.libmyCF.connector.sqlserver.user
        self.passwd = self.libmyCF.connector.sqlserver.passwd

        
        
        #self.connect(self.buttonBox, QtCore.SIGNAL("accepted()"),self, QtCore.SLOT("accept()"))
        self.connect(self.pushButton_apply, QtCore.SIGNAL("clicked()"),self.accept)
        #self.connect(self.pushButton_apply, QtCore.SIGNAL("clicked()"),QtCore.SLOT("accept()"))
        self.connect(self.buttonBox, QtCore.SIGNAL("rejected()"),self, QtCore.SLOT("reject()"))
        
        self.pushButton_directoryexport.clicked.connect(self.setExportFile) 
        self.pushButton_fileimport.clicked.connect(self.setImportFile)
        
        #self.connect(self.lineEdit, QtCore.SIGNAL("textEdited (const QString &)"), self.lineEdit_textEdited)
        
        # file_type = [description with file extenxion, iconpath']
        SQL = ['MySQL dump file (*.sql)',':/icons/sql_icon.jpg'] 
        OWL = ['OWL ontology file (*.rdf)',':/icons/rdf_icon.jpg']
        self.file_types = [SQL, OWL]
        self.filename = "" 

        self.ignore_index_change = True
        index = 1
        for i in range(len(self.file_types)):#self.file_types:
            self.comboBox_filetype_export.insertItem (index, QtGui.QIcon(self.file_types[i][1]),QtCore.QString.fromUtf8(self.file_types[i][0]))
            self.comboBox_filetype_import.insertItem (index, QtGui.QIcon(self.file_types[i][1]),QtCore.QString.fromUtf8(self.file_types[i][0]))
            index += 1
        self.ignore_index_change = False
        
        self.pushButton_fileimport.setEnabled(True)  
        
    def reset_settings(self):
        self.lineEdit_directoryexport.setText("")
        self.lineEdit_filenameimport.setText("")
        self.lineEdit_filenameexport.setText("")
        self.pushButton_apply.setEnabled(False)        
                    
    @QtCore.pyqtSignature("int")
    def on_comboBox_filetype_import_currentIndexChanged(self,index):
        if not self.ignore_index_change :
            self.reset_settings()
            
    @QtCore.pyqtSignature("int")
    def on_comboBox_filetype_export_currentIndexChanged(self,index):
        if not self.ignore_index_change :
            self.reset_settings()

    @QtCore.pyqtSignature("int")
    def on_tabWidget_currentChanged(self,index):
        self.reset_settings()
          
                    
    def setExportFile(self):    
        options = QtGui.QFileDialog.DontResolveSymlinks | QtGui.QFileDialog.ShowDirsOnly
        directory = QtGui.QFileDialog.getExistingDirectory(self,
                "QFileDialog.getExistingDirectory()",
                self.lineEdit_directoryexport.text(), options)
        if directory:
            self.lineEdit_directoryexport.setText(directory)   
            name = self.db_name
            time_backup = time.strftime('%Y%m%d_%H%M') 
            type_desc = self.file_types[self.comboBox_filetype_export.currentIndex()][0]
            index = type_desc.find('*')
            extension= type_desc[index+2:index+5]
            self.filename = "%s_%s.%s"%(name,time_backup,extension)
            self.lineEdit_filenameexport.setText(self.filename)    
            self.pushButton_apply.setEnabled(True)
            self.filename = os.path.join(str(self.lineEdit_directoryexport.text()),self.filename)
            #print self.filename
            
    def setImportFile(self):
        dialog = QtGui.QFileDialog(self)
        dialog.setFileMode(QtGui.QFileDialog.AnyFile)
        index= self.comboBox_filetype_import.currentIndex()
        dialog.setNameFilter(self.file_types[index][0])
        if not dialog.exec_():
            # exit if cancel
            return
          
        fileNames = dialog.selectedFiles()
        targetfile = fileNames.takeFirst()
        self.lineEdit_filenameimport.setText(targetfile)
        self.pushButton_apply.setEnabled(True)
        self.filename = str(targetfile)
        #print self.filename
            
#    def lineEdit_textEdited(self) :
#        import re
#        self.comboBox_find_AE.clear()        
#        liste = []      
#        texte = self.lineEdit.text()
#        if len(self.lineEdit.text()) > 2:
#            self.lineEdit.setText(texte)   

    def accept(self):
        extension = self.filename[len(self.filename)-3:]
        
        if self.tabWidget.currentIndex() == 0 : #import database
            if extension == 'sql':
                db_name = "test"
                try:
                    os.system("mysql -h "+self.host+" -u "+self.user+" -p"+self.passwd+" "+self.db_name+" < "+self.filename)
                except OSError, e:
                    print >>sys.stderr, "Execution failed:", e
            if extension == 'rdf':
                QtGui.QMessageBox.information(self,"Import Database","Not implemented yet...")  
                return
                
            
        if self.tabWidget.currentIndex() == 1 : #export database
            if extension == 'sql':
                try:
                    os.system("mysqldump --add-drop-table -c -h "+self.host+" -u "+self.user+" -p"+self.passwd+" "+self.db_name+" > "+self.filename)
                except OSError, e:
                    print >>sys.stderr, "Execution failed:", e
                #QtGui.QMessageBox.information(self,"Export Database","Not implemented yet...")
                #return  
            if extension == 'rdf':
                QtGui.QMessageBox.information(self,"Export Database","Not implemented yet...")
                return  
            

        QtGui.QDialog.accept(self)